package com.sl.au.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.sl.au.entity.Account;
import com.sl.au.entity.ArchiveReportInfo;
import com.sl.au.entity.BussinessContent;
import com.sl.au.entity.Comment;
import com.sl.au.entity.Division;
import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventReport;
import com.sl.au.entity.EventTask;
import com.sl.au.entity.EventType;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.Module;
import com.sl.au.entity.News;
import com.sl.au.entity.Option;
import com.sl.au.entity.Role;
import com.sl.au.entity.TimeOutReceiveRegister;
import com.sl.au.entity.User;
import com.sl.au.service.ArchiveReportInfoService;
import com.sl.au.service.BussinessContentService;
import com.sl.au.service.CommentService;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.EventReportService;
import com.sl.au.service.EventTypeService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.ModuleService;
import com.sl.au.service.NewsService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.RoleService;
import com.sl.au.service.TimeOutTaskService;
import com.sl.au.service.UserService;
import com.sl.utils.ExdeUtil;

/**
 * 任务督办
 * 
 * @author yangdi
 *
 */
@RestController
@RequestMapping(value = "/ui/taskSupervision")
public class TaskSupervisionController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private OptionService optionService;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	EventTypeService eventTypeService;
	@Autowired
	ModuleService moduleService;
	@Autowired
	private TimeOutTaskService timeOutTaskService;
	@Autowired
	EventRegisterService eventRegisterService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView, HttpServletRequest request) {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		modelAndView.setViewName("mobile/taskSupervision/taskSupervisionIndex");
		modelAndView.addObject("identify", identify);
		return modelAndView;
	}

	@RequestMapping(value = "findAllTaskSupervision", method = RequestMethod.GET)
	public Map<String, Object> findAllTaskSupervision() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<EventRegister> receives = null;
		List<Option> options = this.optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "已分配");
		String taskStateId = "";
		if (options.size() > 0) {
			taskStateId = options.get(0).getId();
		}
		receives = timeOutTaskService.getTimeOutTaskForReceive(0, Integer.MAX_VALUE, taskStateId, "1", null, null,
				null);

		List<TimeOutReceiveRegister> deals = null;
		options.clear();
		options = this.optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "处理中");
		taskStateId = "";
		if (options.size() > 0) {
			taskStateId = options.get(0).getId();
		}
		deals = timeOutTaskService.getTimeOutTaskForDeal(0, Integer.MAX_VALUE, taskStateId, "1", null, null, null);

		map.put("receives", receives);
		map.put("deals", deals);

		return map;
	}

	@RequestMapping("/getTaskById/{id}")
	public Map<String, Object> getTaskById(@PathVariable("id") String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		EventRegister eventRegister = eventRegisterService.getRepository().findOne(id);
		map.put("eventRegister", eventRegister);
		return map;
	}

	@RequestMapping("/supervision/{type}/{id}")
	public Map<String, Object> supervision(@PathVariable("type") String type, @PathVariable("id") String id) {

		Map<String, Object> map = new HashMap<String, Object>();
		sendMessageToOne(type, id);
		map.put("msg", "(" + type + ":" + id + ")\n督办成功");
		return map;
	}

	private void sendMessageToOne(String type, String id) {

		EventRegister register = eventRegisterService.getRepository().findOne(id);
		// 接收该事件的操作人
		if (register != null) {
			String time = register.getCreateTime().toString();
			if ("receive".equals(type)) {

				this.sendMsgToDealUser(register, register.getRegisterEventToNetGrid(),
						register.getRegisterEventType().getId(), register.getRegisterEventIdentify(),
						register.getRegisterEventAdress());

			}
			if ("deal".equals(type)) {
				String content = "【悦来城市综合服务平台】您于[" + time + "]上报的[" + register.getRegisterEventName() + "]已被您接收,请尽快处理!";
				Option op = this.optionService.findByGroupAndExtended1("通知短信格式", "督办处理通知");
				if (op != null) {
					content = op.getTitle();
				}
				content = content.replace("{0}", time);
				content = content.replace("{1}", register.getRegisterEventName());
				EventTask task = eventRegisterService.findTask(id, register.getRegisterEventState());
				String phone = task.getEventTaskUser().getContactType();
				Map<String, Object> mapTemp = this.sendMessage(phone, content);
				if (mapTemp.get("code") != null && mapTemp.get("code").equals(1)) {
					// 是否记录日志
					operateLogService.log(this.getMyAccount().getUser(), "督办处理通知", content);
				} else {
					operateLogService.log(this.getMyAccount().getUser(), "督办处理通知", "发送通知消息失败!");
				}
			}

		}

	}

	private void sendMsgToDealUser(EventRegister register, GridAreaInfo info, String eventTypeId, String identify,
			String adress) {
		try {
			if (info != null) {
				List<User> users = this.userService.getRepository().findUsersByEventTypeAndGrid(eventTypeId,
						info.getId());
				String phoneList = "";
				if (users != null) {
					for (int i = 0; i < users.size(); i++) {
						if (users.get(i).getContactType().length() == 11) {// 手机号码
							phoneList += users.get(i).getContactType() + ",";
						}
					}
				}
				if (phoneList != "") {
					phoneList = phoneList.substring(0, phoneList.length() - 1);
					// 短信通知
					String time = register.getCreateTime().toString();
					String content = "【悦来城市综合服务平台】您于[" + time + "]上报的[" + register.getRegisterEventName()
							+ "]已分配,请尽快接收!";
					Option op = this.optionService.findByGroupAndExtended1("通知短信格式", "督办接收通知");
					if (op != null) {
						content = op.getTitle();
					}
					content = content.replace("{0}", time);
					content = content.replace("{1}", register.getRegisterEventName());
					Map<String, Object> mapTemp = this.sendMessage(phoneList, content);
					if (mapTemp.get("code") != null && mapTemp.get("code").equals(1)) {
						// 是否记录日志
						operateLogService.log(this.getMyAccount().getUser(), "督办接收通知", content);
					} else {
						operateLogService.log(this.getMyAccount().getUser(), "督办接收通知", "发送案件到达通知失败!");
					}
					// ------------
				}
			}
		} catch (Exception ex) {

		}

	}

}
